// mainwindow.cpp
#include "mainwindow.h"
#include <QMenuBar>
#include <QStatusBar>
#include <QDockWidget>
#include <QMessageBox>
#include <QFileDialog>
#include <QDebug>
#include "drawingarea.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    qDebug() << "MainWindow constructing...";
    qDebug() << "Checking resources:";
    qDebug() << " - Wire red exists:" << QFile(":/components/wire_red.png").exists();

    // 先初始化核心部件
    drawingArea = new DrawingArea(this);
    if(!drawingArea) {
        qCritical() << "Failed to create DrawingArea";
        return;
    }

    componentInfoWidget = new ComponentInfoWidget(this);
    componentLibrary = new ComponentLibrary(this);

    qDebug() << "Core widgets created";

    // 然后设置UI
    try {
        createActions();
        createMenus();
        createToolBars();
        createStatusBar();
        createDockWindows();
        qDebug() << "UI setup completed";
    } catch (...) {
        qCritical() << "Exception during UI setup";
    }

    setCentralWidget(drawingArea);
    qDebug() << "MainWindow constructed successfully";
    componentInfoWidget = new ComponentInfoWidget(this);
    QDockWidget *infoDock = new QDockWidget(tr("Component Info"), this);
    infoDock->setWidget(componentInfoWidget);
    addDockWidget(Qt::RightDockWidgetArea, infoDock);

    componentLibrary = new ComponentLibrary(this);
    QDockWidget *libraryDock = new QDockWidget(tr("Component Library"), this);
    libraryDock->setWidget(componentLibrary);
    addDockWidget(Qt::LeftDockWidgetArea, libraryDock);

    drawingArea->setAcceptDrops(true);

    connect(componentLibrary, &ComponentLibrary::componentSelectedForPlacement,
            drawingArea, &DrawingArea::setCurrentComponent);
    qDebug() << "componentLibrary->drawingArea connection:" <<
        (connect(componentLibrary, &ComponentLibrary::componentSelectedForPlacement,
                 drawingArea, &DrawingArea::addComponent) ? "success" : "failed");

    connect(drawingArea, &::DrawingArea::componentSelected, [this]() {
        componentLibrary->clearSelection();
    });

    connect(drawingArea, &DrawingArea::componentSelected,
            componentInfoWidget, &ComponentInfoWidget::showComponentInfo);
    qDebug() << "drawingArea->componentInfoWidget connection:" <<
        (connect(drawingArea, &DrawingArea::componentSelected,
                 componentInfoWidget, &ComponentInfoWidget::showComponentInfo) ? "success" : "failed");

    connect(componentLibrary, &ComponentLibrary::componentDoubleClicked,
            [this](Component* comp) {
                if (comp) {
                    QPointF dropPos = drawingArea->mapToScene(drawingArea->viewport()->rect().center());
                    drawingArea->addComponentAtPosition(comp, dropPos);
                }
            });

    connect(drawingArea, &DrawingArea::componentRequested,
            [this](const QString& name, const QPointF& position) {
                Component* comp = componentLibrary->getComponentByName(name);
                if (comp) {
                    drawingArea->addComponentAtPosition(comp, position);
                }
            });
}

void MainWindow::createActions()
{
    newAct = new QAction(tr("&New"), this);
    newAct->setShortcut(QKeySequence::New);
    newAct->setStatusTip(tr("Create a new circuit design"));
    connect(newAct, &QAction::triggered, drawingArea, &DrawingArea::clear);

    openAct = new QAction(tr("&Open..."), this);
    openAct->setShortcut(QKeySequence::Open);
    openAct->setStatusTip(tr("Open an existing circuit design"));
    connect(openAct, &QAction::triggered, [this]() {
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open Circuit Design"), "",
                                                        tr("Circuit Files (*.circuit)"));
        if (!fileName.isEmpty())
            drawingArea->loadFromFile(fileName);
    });

    saveAct = new QAction(tr("&Save"), this);
    saveAct->setShortcut(QKeySequence::Save);
    saveAct->setStatusTip(tr("Save the circuit design to disk"));
    connect(saveAct, &QAction::triggered, [this]() {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save Circuit Design"), "",
                                                        tr("Circuit Files (*.circuit)"));
        if (!fileName.isEmpty())
            drawingArea->saveToFile(fileName);
    });

    saveAsAct = new QAction(tr("Save &As..."), this);
    saveAsAct->setStatusTip(tr("Save the circuit design under a new name"));
    connect(saveAsAct, &QAction::triggered, [this]() {
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save Circuit Design As"), "",
                                                        tr("Circuit Files (*.circuit);;PNG Image (*.png);;JPEG Image (*.jpg)"));
        if (!fileName.isEmpty()) {
            if (fileName.endsWith(".png") || fileName.endsWith(".jpg"))
                drawingArea->exportToImage(fileName);
            else
                drawingArea->saveToFile(fileName);
        }
    });

    exitAct = new QAction(tr("E&xit"), this);
    exitAct->setShortcut(QKeySequence::Quit);
    exitAct->setStatusTip(tr("Exit the application"));
    connect(exitAct, &QAction::triggered, this, &QWidget::close);

    aboutAct = new QAction(tr("&About"), this);
    aboutAct->setStatusTip(tr("Show the application's About box"));
    connect(aboutAct, &QAction::triggered, []() {
        QMessageBox::about(nullptr, tr("About EDA Circuit Designer"),
                           tr("An EDA software for circuit design and simulation."));
    });
}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAct);
    fileMenu->addAction(openAct);
    fileMenu->addAction(saveAct);
    fileMenu->addAction(saveAsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));
    // Add edit actions later

    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
}

void MainWindow::createToolBars()
{
    fileToolBar = addToolBar(tr("File"));
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);

    editToolBar = addToolBar(tr("Edit"));
    // Add edit actions later
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void MainWindow::createDockWindows()
{
    // Already created in constructor
}

MainWindow::~MainWindow()
{
}
